from django.http import JsonResponse
from main_app.models import User
from django.views.decorators.csrf import csrf_exempt
import os
from avatar_update.settings import BASE_DIR
import time
import random
import threading


@csrf_exempt
def upload(request):
    username = request.POST.get('username')
    avatar_obj = request.FILES.get('avatar')
    q = User.objects.filter(username=username).first()

    if q.avatar_name:
        threading.Thread(target=os.remove(os.path.join(BASE_DIR, 'media', q.avatar_name))).start()

    avatar_name = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) + str(
        random.randint(0, 10000)) + '.' + avatar_obj.name.split('.')[-1]

    q.avatar_name = avatar_name
    q.save()

    with open(os.path.join(BASE_DIR, 'media', avatar_name), 'wb') as f:
        f.write(avatar_obj.file.read())
        f.close()

    return JsonResponse({'code': 200, 'msg': '上传成功'})
